package com.usesion.service.impl;

import com.usesion.base.shiro.UserRealm;
import com.usesion.common.constant.Constants;
import com.usesion.base.shiro.ShiroUtils;
import com.usesion.entity.Role;
import com.usesion.entity.User;
import com.usesion.entity.UserRole;
import com.usesion.mapper.RoleMapper;
import com.usesion.mapper.UserMapper;
import com.usesion.mapper.UserRoleMapper;
import com.usesion.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @desc: 用户
 * @author: XT
 */
@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 根据条件分页查询用户对象
     *
     * @param user 用户信息
     *
     * @return 用户信息集合信息
     */
    @Override
    public List<User> selectUserList(User user) {
        return userMapper.selectUserList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public User selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过手机号码查询用户
     *
     * @param telephone
     * @return 用户对象信息
     */
    @Override
    public User selectUserByTelephone(String telephone) {
        return userMapper.selectUserByTelephone(telephone);
    }

    /**
     * 通过邮箱查询用户
     *
     * @param email 邮箱
     * @return 用户对象信息
     */
    @Override
    public User selectUserByEmail(String email) {
        return userMapper.selectUserByEmail(email);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public User selectUserById(Integer userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public int deleteUserById(Integer userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int batchDeleteUser(Integer[] ids) {
        userRoleMapper.deleteUserRole(ids);
        return userMapper.batchDeleteUser(ids);
    }

    /**
     * 保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int saveUser(User user) {
        int count = 0;
        Integer userId = user.getId();
        if (userId != null) {
            user.setUpdateBy(ShiroUtils.getUserName());
            count = updateUser(user);
            userRoleMapper.deleteUserRoleByUserId(userId);
            insertUserRole(user);
        } else {
            user.generateRandomSalt();
            user.setPassword(new UserRealm().encryptPassword(user.getUserName(), user.getPassword(), user.getSalt()));
            user.setCreateBy(ShiroUtils.getUserName());
            count = userMapper.insertUser(user);
            insertUserRole(user);
        }
        return count;
    }

    /**
     * 修改用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUser(User user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetUserPwd(User user) {
        user.generateRandomSalt();
        user.setPassword(new UserRealm().encryptPassword(user.getUserName(), user.getPassword(), user.getSalt()));
        return updateUser(user);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(User user) {
        // 新增用户与角色管理
        List<UserRole> list = new ArrayList<UserRole>();
        for (Integer roleId : user.getRoleIds()) {
            UserRole ur = new UserRole();
            ur.setUserId(user.getId());
            ur.setRoleId(roleId);
            list.add(ur);
        }
        if (list.size() > 0) {
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户名
     * @return
     */
    @Override
    public String checkUserNameUnique(String userName) {
        int count = userMapper.checkUserNameUnique(userName);
        if (count > 0) {
            return Constants.USER_NAME_NOT_UNIQUE;
        }
        return Constants.USER_NAME_UNIQUE;
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户名
     * @return
     */
    @Override
    public String checkPhoneUnique(User user) {
        if (user.getId() == null) {
            user.setId(-1);
        }
        Integer userId = user.getId();
        User info = userMapper.checkTelephoneUnique(user.getTelephone());
        if (info != null && info.getId() != null && !info.getId().equals(userId)) {
            return Constants.USER_PHONE_NOT_UNIQUE;
        }
        return Constants.USER_PHONE_UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户
     * @return
     */
    @Override
    public String checkEmailUnique(User user) {
        if (user.getId() == null) {
            user.setId(-1);
        }
        Integer userId = user.getId();
        User info = userMapper.checkEmailUnique(user.getEmail());
        if ( info != null && info.getId() != null && !info.getId().equals(userId)) {
            return Constants.USER_EMAIL_NOT_UNIQUE;
        }
        return Constants.USER_EMAIL_UNIQUE;
    }

    /**
     * 查询用户所属角色组
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(Integer userId) {
        List<Role> list = roleMapper.selectRolesByUserId(userId);
        StringBuffer idsStr = new StringBuffer();
        for (Role role : list) {
            idsStr.append(role.getName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }
}
